package cn.turing.firecontrol.admin.rest;

import cn.turing.firecontrol.admin.config.GiteeHttpClient;
import cn.turing.firecontrol.common.msg.ObjectRestResponse;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * @ClassName GiteeController
 * @Author YH
 * @Date 2021/7/17
 * @Version 1.0
 */

@Controller
@RequestMapping("/gitlogin")
public class GiteeController {
    /**
     * gitee授权中提供的 appid 和 appkey
     */
    @Value("${gitee.oauth.clientid}")
    public String CLIENTID;

    @Value("${gitee.oauth.clientsecret}")
    public String CLIENTSECRET;

    @Value("${gitee.oauth.callback}")
    public String URL;

    /**
     * 请求授权页面
     */
    @RequestMapping(value = "/auth",method = RequestMethod.GET)
    public String giteeAuth(HttpSession session) {
        // 用于第三方应用防止CSRF攻击
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        session.setAttribute("state", uuid);

        // Step1：获取Authorization Code
        String url = "https://gitee.com/oauth/authorize?response_type=code" +
                "&client_id=" + CLIENTID +
                "&redirect_uri=" + URLEncoder.encode(URL) +
                "&state=" + uuid +
                "&scope=user_info";
        return "redirect:" + url;
        //return new ObjectRestResponse<>().data(url);
    }

    /**
     * 授权回调
     */
    @RequestMapping(value = "/success",method = RequestMethod.GET)
    public String qqCallback(HttpServletRequest request, Model model) throws Exception {
        HttpSession session = request.getSession();
        // 得到Authorization Code
        String code = request.getParameter("code");
        // 我们放在地址中的状态码
        String state = request.getParameter("state");
        String uuid = (String) session.getAttribute("state");

        // 验证信息我们发送的状态码
        if (null != uuid) {
            // 状态码不正确，直接返回登录页面
            if (!uuid.equals(state)) {
                return "redirect:http://localhost:9527";
            }
        }

        // Step2：通过Authorization Code获取Access Token
        String url = "https://gitee.com/oauth/token?grant_type=authorization_code" +
                "&client_id=" + CLIENTID +
                "&client_secret=" + CLIENTSECRET +
                "&code=" + code +
                "&redirect_uri=" + URL;
        JSONObject accessTokenJson = GiteeHttpClient.getAccessToken(url);

        // Step3: 获取用户信息
        url = "https://gitee.com/api/v5/user?access_token=" + accessTokenJson.get("access_token");
        JSONObject jsonObject = GiteeHttpClient.getUserInfo(url);

        System.out.println(jsonObject);

        System.out.println(jsonObject.get("name"));

        model.addAttribute("name", jsonObject.get("name"));


        /**
         * 获取到用户信息之后，就该写你自己的业务逻辑了
         */
        return "redirect:http://localhost:9527/#/gailan/overView";
    }
}

